package cn.sunshine.controller;

import cn.sunshine.domain.User;

import cn.sunshine.handler.UserFallBackHandler;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RefreshScope  //刷新配置
@RestController
public class UserController {

    @Value("${test}")
    private Long test;

    @GetMapping("/user/{id}")
    @SentinelResource(value="user",
            blockHandler = "exceptionHandler",
            blockHandlerClass = UserFallBackHandler.class,
            fallback = "getUserByIdFallBack")
    public User getById(@PathVariable Long id){
        getUserById(id);
        System.out.println("测试配置test=" + test);
        return new User(id,"zs:"+id, "我是zs");
    }

    public User getUserById(Long id){
        int i = 1 / 0;
        return User.builder().id(test).intro("遭了嘛").name("我不管嘛").build();
    }

    // 限流与阻塞处理 : 参数要和 被降级的方法参数一样
    public User getUserByIdFallBack(Long id) {
        System.out.println("限流了...");
        return new User(-1L,"限流了111111111","限流了");
    }
/*参数限流*/
    //限流降级
    @SentinelResource(value="/parameterLimit",blockHandler="parameterLimitHandler")
    @GetMapping(value="/parameterLimit/{p1}/{p2}")
    public String parameterLimit(@PathVariable("p1") String p1 , @PathVariable("p2") String p2){
        return "parameterLimit方法调用成功...";
    }
    // 限流与阻塞处理
    public String parameterLimitHandler(@PathVariable("p1") String p1 ,@PathVariable("p2") String p2,BlockException ex) {
        return "限流了..."+p1+p2;
    }
}

